package com.reebake.ideal.mybatis.core;

import cn.hutool.core.util.ObjUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.reebake.ideal.mybatis.properties.PaginationProperties;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class PageResultSerializer extends JsonSerializer<PageResult> {
    private final PaginationProperties paginationProperties;

    public PageResultSerializer(PaginationProperties paginationProperties) {
        this.paginationProperties = paginationProperties;
    }

    @Override
    public void serialize(PageResult value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        Map<String, Object> result = new LinkedHashMap<>();
        Collection<?> records = new ArrayList<>();
        long total = 0;
        if (ObjUtil.isNotNull(value)) {
            records = value.getRecords();
            total = value.getTotal();
        }
        result.put(paginationProperties.getRecordsParameterName(), records);
        result.put(paginationProperties.getTotalParameterName(), total);
        gen.writeObject(result);
    }
}
